-- Author: shunguo.chen
-- Date: 2016-06-17 11:42:45
--
-- MailController
--

local MailView = import("..views.MailView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)
	
end

function ClassRef:init()
	self._model = app:getInst("MailModel")

	self._showOver = true
	self._tempActions = nil

end

function ClassRef:removeListeners()
	self.super.removeListeners(self)

end

function ClassRef:listEvent()
    return {
	    "mail_numChange",
	    "onReconnectSuccessed"
	}
end

function ClassRef:onEvent(eventName, data)
	if eventName == "mail_numChange" then
		
	elseif eventName == "onReconnectSuccessed" then
		self._model:removeExpiredMails()
	end
end

function ClassRef:openView(data)
	if cc.isDead(self._view) then
		self._view = MailView.new(app.mvc.VIEWTYPE_BLUR)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._view, data)

	-- app:sendMsg("MallModel", "reqCheckMidasPermission", true)
	
	self._view:show()
	self._model:getMails(function(mails)
		self:refreshMailList(mails)
	end)
end
function ClassRef:clearView()
	if self._view then 
		self._tempActions = nil
		self._view = nil 
	end
end

function ClassRef:writeMail(uid)
	display.pushToast(L("tips_1110010"))
end

function ClassRef:onOperate(operate, data)
	-- print("MailController:onMailOperate = " .. operate)
	if operate == "reqMails" then
		self._model:queryMails(data)
	elseif operate == "reqDetail" then
		self._model:queryMailDetail(data)
	elseif operate == "delete" then
		self._model:deleteMail(data)
	elseif operate == "getItems" then
		self._model:takeMailsItems(data)
	elseif operate == "openWritePanel" then
		-- TODO
		local messageBox = display.newMessageBox(L("tips_1110010"))
		UIHandler:addPopDialog(messageBox)
	elseif operate == "openURl" then
		app.channelAPI:openURL(data)
	elseif operate == "checkPermission" then
		-- 有赠钻时检测支付授权
		app:sendMsg("MallModel", "reqCheckMidasPermission")
	end
end

function ClassRef:appendMails(mails, isNew)
	if not self:isViewAlive() then return end
	isNew = isNew or false

	if not self._showOver then
		self._tempActions = self._tempActions or {}
		table.insert(self._tempActions, {op="append", mails=mails, isNew=isNew})
		return
	end

	-- print("MailController:appendMails isNew = " .. tostring(isNew))

	local listView = self._view:getMailList()
	local items = listView:getItems()
	local firstItem = nil
	for i,mail in ipairs(mails) do
		local render = listView:createRender(i)
		render:setData(mail)
		render:onBtnClick(function()
			self._view:setCurMail(render)
		end)
		if isNew then
			listView:insertCustomItem(render, i-1)
		else
			listView:pushBackCustomItem(render)
		end
		if firstItem == nil then
			firstItem = render
		end
	end

	listView:refreshView()
	self._view:performWithDelay(function()
		self._view:setCurMail(firstItem)
	end, 0)
end

function ClassRef:mailUpdate(mail)
    if not mail then 
        dump("MailController:mailUpdate() mail is nil")
        return 
    end
	if not self:isViewAlive() then return end
	local listView = self._view:getMailList()
	local items = listView:getItems()
	for i,item in ipairs(items) do
		if item:getData() and item:getData().uid == mail.uid then
			item:setData(mail)
			if item:isSelected() then
				self._view:refreshMailContent()
			end
			break
		end
	end
end

function ClassRef:mailDelete(uids)
	if not self:isViewAlive() then return end

	if not self._showOver then
		self._tempActions = self._tempActions or {}
		table.insert(self._tempActions, {op="delete", uids=uids})
		return
	end

	local listView = self._view:getMailList()
	local items = listView:getItems()
	local isSelectItemDelete = false
	local selectRender
	for i=#items,1,-1 do
		local item = items[i]
		if item:getData() then
			if table.indexof(uids, item:getData().uid) then
				if item:isSelected() then
					isSelectItemDelete = true
					if #uids == 1 then
						-- 如果是删除单个邮件，优先选择下一封邮件，没有就选择前一封邮件
						selectRender = items[i + 1] or items[i - 1]
					end
				end
				listView:removeItem(i-1)
			end
		end
	end
	if isSelectItemDelete then
		self._view:removeCurMail()
		self._view:setCurMail(selectRender)
	end
end

-----------------------------------------------------------------------
function ClassRef:refreshMailList(mails)
	if not self:isViewAlive() then return end
	
	-- print(self:getControllerName() .. ":refreshMailList mails.len = " .. #mails)
	local listView = self._view:getMailList()
	listView:stopAllActions()
	
	local len = #mails
	local curIdx = 0
	local function addMail()
		curIdx = curIdx + 1
		if curIdx <= len then
			local render = listView:createRender(curIdx)
			render:setData(mails[curIdx])
			render:onBtnClick(function()
				self._view:setCurMail(render)
			end)
			listView:pushBackCustomItem(render)
		else
			listView:stopAllActions()
			self._showOver = true
			if self._tempActions then
				for i,v in ipairs(self._tempActions) do
					if v.op == "append" then
						self:appendMails(v.mails, v.isNew)
					elseif v.op == "delete" then
						self:mailDelete(v.uids)
					end
				end
				self._tempActions = nil
			end
		end
	end
	if len > 0 then
		self._showOver = false
		addMail()
		listView:schedule(addMail, 0)
	end
	self._view:setCurMail()
end

return ClassRef